/*
 * @Author: Orangepi - xcy2001@sina.cn
 * @Date: 2022-01-02 00:42:33
 * @LastEditTime: 2022-01-02 02:14:53
 * @LastEditors: Orangepi - xcy2001@sina.cn
 * @Description:
 * @FilePath: \college-application-enrollment-web\cae-web\src\network\request.js
 */
import axios from 'axios'
//这里引用了element的loading全屏加载
import { Loading } from "element-ui";

const service = axios.create({
    baseURL: 'https://qc6d85.app.cloudendpoint.cn/api',
    timeout: 8000 // 设置请求超时时间
})
let loading = "";

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        //  console.log("请求处理中...");
        // 在请求发送之前做一些处理
        if (!(config.headers['Content-Type'])) {
            loading = Loading.service({
                lock: true,
                text: "加载中...",
                spinner: "el-icon-loading",
                background: "rgba(255,255,255,0.7)",
                customClass: "request-loading",
            });
            if (config.headers['Content-Type'] === 'multipart/form-data') {

            } else if (config.method === 'post') {
                config.headers['Content-Type'] =
                    'application/json;charset=UTF-8'
                for (var key in config.data) {
                    if (config.data[key] === '') {
                        delete config.data[key]
                    }
                }
                config.data = JSON.stringify(config.data)
            } else if (config.method === 'get') {
                config.headers['Content-Type'] =
                    'application/x-www-form-urlencoded;charset=UTF-8';
            } else {
                config.headers['Content-Type'] =
                    'application/x-www-form-urlencoded;charset=UTF-8';
                config.data = JSON.stringify(config.data)
            }
        }
        const token = localStorage.jwt;
        if (token) {
            // console.log("已经添加jwt");
            config.headers['Authorization'] = token;
        }
        // console.log("请求处理完成");
        return config
    },
    (error) => {
        loading.close();
        // 发送失败
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        //  console.log("22");
        loading.close();
        // dataAxios 是 axios 返回数据中的 data
        // loadingInstance.close();
        const dataAxios = response.data
            // 这个状态码是和后端约定的

        return dataAxios
    },
    (error) => {
        loading.close();
        return Promise.reject(error)
    }
)

export default service
